package com.partner.share.work.email.service.impl;

import com.partner.share.work.email.config.EmailConfig;
import com.partner.share.work.email.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2019年09月19日 10:20:00
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    MailSender javaMailSender;
    @Autowired
    EmailConfig emailConfig;

    @Autowired
    JavaMailSender mailSender;

    @Override
    public  String getEmailCode() {
        double random = Math.random()*1000000;
        String result = String.valueOf(random);
        return result.substring(0,result.indexOf("."));
    }

    @Override
    public void sendEmail(String code,String to) {

        // 构造Email消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailConfig.getUsername());
        message.setTo(to);
        message.setSubject("注册验证码");
        message.setText(String.format("【共享办公】你的验证码为%s,赶快完成验证，5分钟后验证码就过期啦~如非本人操作就忽略吧",code));
        javaMailSender.send(message);

    }

    @Override
    public void sendEmailTemplate(String code,String to) throws MessagingException, UnsupportedEncodingException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true,"utf-8");
        //这里可以自定义发信名称比如：爪哇笔记
        helper.setFrom(emailConfig.getUsername(),"共享办公");
        helper.setTo(to);
        helper.setSubject("注册验证码");
        helper.setText("【共享办公】你的验证码为<a href='#' style='color:red'>"+code+"</a>,赶快完成验证，5分钟后验证码就过期啦~如非本人操作就忽略吧");
        mailSender.send(message);
    }
}
